package com.techsoul.module.tms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.config.properties.LbsApiProperties;
import com.techsoul.common.core.constant.Constants;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.LbsApiResponseVo;
import com.techsoul.common.core.pojo.vo.OrgVo;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.http.HttpClientUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.CustomerMapper;
import com.techsoul.module.basic.mapper.TBmLocationMapper;
import com.techsoul.module.basic.mapper.WarehouseMapper;
import com.techsoul.module.basic.pojo.entity.Customer;
import com.techsoul.module.basic.pojo.entity.TBmLocation;
import com.techsoul.module.basic.pojo.entity.Warehouse;
import com.techsoul.module.basic.pojo.vo.TBmLocationVo;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.order.mapper.PurchaseOrderItemMapper;
import com.techsoul.module.order.mapper.PurchaseOrderMapper;
import com.techsoul.module.order.pojo.entity.PurchaseOrder;
import com.techsoul.module.order.pojo.entity.PurchaseOrderItem;
import com.techsoul.module.pms.enmus.WmsOutStatusEnum;
import com.techsoul.module.pms.mapper.TWhWarehouseCustomerMaterialMapper;
import com.techsoul.module.pms.mapper.TbWmsMaterialDeliveryLineMapper;
import com.techsoul.module.pms.mapper.TbWmsMaterialDeliveryMapper;
import com.techsoul.module.pms.pojo.entity.TWhWarehouseCustomerMaterial;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialDelivery;
import com.techsoul.module.pms.pojo.entity.TbWmsMaterialDeliveryLine;
import com.techsoul.module.pms.pojo.param.TbWmsMaterialDeliverySaveParam;
import com.techsoul.module.pms.pojo.vo.TWhWarehouseCustomerMaterialVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryLineVo;
import com.techsoul.module.pms.pojo.vo.TbWmsMaterialDeliveryVo;
import com.techsoul.module.pms.service.IBmsAllGeneralSeqTabService;
import com.techsoul.module.pms.service.ITWhWarehouseCustomerMaterialService;
import com.techsoul.module.system.mapper.OrgMapper;
import com.techsoul.module.tms.mapper.TFeeRoutePriceNewMapper;
import com.techsoul.module.tms.mapper.TFoFreightOrderItemMapper;
import com.techsoul.module.tms.mapper.TFoFreightOrderMapper;
import com.techsoul.module.tms.mapper.TFoTransitRouteMapper;
import com.techsoul.module.tms.pojo.entity.TFeeRoutePriceNew;
import com.techsoul.module.tms.pojo.entity.TFoFreightOrder;
import com.techsoul.module.tms.pojo.entity.TFoFreightOrderItem;
import com.techsoul.module.tms.pojo.entity.TFoTransitRoute;
import com.techsoul.module.tms.pojo.param.TFeeRoutePriceNewSearchParam;
import com.techsoul.module.tms.pojo.param.TFoFreightOrderSaveParam;
import com.techsoul.module.tms.pojo.param.TFoFreightOrderSearchParam;
import com.techsoul.module.tms.pojo.vo.TFeeRoutePriceNewVo;
import com.techsoul.module.tms.pojo.vo.TFoFreightOrderItemVo;
import com.techsoul.module.tms.pojo.vo.TFoFreightOrderVo;
import com.techsoul.module.tms.pojo.vo.TFoTransitRouteVo;
import com.techsoul.module.tms.service.ITFoFreightOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Optional;

/**
 * 运单主 Service实现
 * 
 * @author liuen
 * @date 2023-05-29
 */

@Service
@Slf4j
@Transactional(readOnly = true)
public class TFoFreightOrderServiceImpl implements ITFoFreightOrderService {

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private LbsApiProperties lbsApiProperties;
    @Autowired
    private TFoFreightOrderMapper mapper;
    @Autowired
    private TFoFreightOrderItemMapper tFoFreightOrderItemMapper;

    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;
    @Autowired
    private PurchaseOrderItemMapper purchaseOrderItemMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private OrgMapper orgMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private TBmLocationMapper tBmLocationMapper;
    @Autowired
    private TFoTransitRouteMapper tFoTransitRouteMapper;
   // @Autowired
   // private TransitRouteMapper transitRouteMapper;
   @Autowired
   private TFeeRoutePriceNewMapper routePriceNewMapper;

    @Autowired
    private TbWmsMaterialDeliveryMapper tbWmsMaterialDeliveryMapper;

    @Autowired
    private TWhWarehouseCustomerMaterialMapper tWhWarehouseCustomerMaterialMapper;
    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private TbWmsMaterialDeliveryLineMapper tbWmsMaterialDeliveryLineMapper;
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IBmsAllGeneralSeqTabService tBmsAllGeneralSeqTabService;

    private static final String LOCATION = "location";
    private static final double EARTH_RADIUS = 6378.137;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(TFoFreightOrderSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        TFoFreightOrder entity = new TFoFreightOrder();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(TFoFreightOrderSaveParam params) {
        TFoFreightOrder entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public TFoFreightOrderVo findById(String id) {
        return this.mapper.findById(id);
    }
    @Override
    public TFoFreightOrderVo getOrderDetail(String orderId) {
        return this.mapper.getOrderDetail(orderId);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<TFoFreightOrderVo> findAll(TFoFreightOrderSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<TFoFreightOrderVo> findAll(TFoFreightOrderSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }
    @Override
    public List<TFeeRoutePriceNewVo> findFtlPerMileRoutepriceUseTariff(PurchaseOrder tFoFreightOrder){
        String custNo = tFoFreightOrder.getCustomerNo();

        String isExpressYn = tFoFreightOrder.getIsHotYn();
        String chargeadjustType = tFoFreightOrder.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("FTL");
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd("*");
        routePriceNewSearchParam.setArrAreaCd("*");
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            return result;
        }

    }
    @Override
    public List<TFeeRoutePriceNewVo> findFtlPerMileRoutepriceUseTariff(TFoFreightOrder tFoFreightOrder){
        String custNo = tFoFreightOrder.getCustomerNo();

        String isExpressYn = tFoFreightOrder.getIsHotYn();
        String chargeadjustType = tFoFreightOrder.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("FTL");
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd("*");
        routePriceNewSearchParam.setArrAreaCd("*");
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            return result;
        }

    }

    @Override
    public List<TFeeRoutePriceNewVo> findPerMileRoutepriceUseTariff(TFoFreightOrderItem freightOrderItem){
        String custNo = freightOrderItem.getCustomerNo();

        String materialType = freightOrderItem.getCargoFreightSpec();
        String isExpressYn = freightOrderItem.getIsHotYn();
        String chargeadjustType = freightOrderItem.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("LTL");
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd("*");
        routePriceNewSearchParam.setArrAreaCd("*");
        routePriceNewSearchParam.setFrtCd("CountCarriage");
        if (!StringUtils.isNull(materialType)) {
            if (materialType.equals("PH")) {
                routePriceNewSearchParam.setChargeAdjustType("volume");
            } else {
                routePriceNewSearchParam.setChargeAdjustType(chargeadjustType);
            }
        } else {
            routePriceNewSearchParam.setChargeAdjustType("*");
        }
        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            return result;
        }
    }
    @Override
    public List<TFeeRoutePriceNewVo> findRoutepriceUseTariff(PurchaseOrderItem freightOrderItem) {

        String custNo = freightOrderItem.getCustomerNo();
        String depart = freightOrderItem.getDeparture();
        String destination = freightOrderItem.getDestination();
        String materialType = freightOrderItem.getSpec();
        String isExpressYn = freightOrderItem.getIsHotYn();
        String chargeadjustType = freightOrderItem.getShipbyQtyWeightOrPack();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("LTL");
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd(depart);
        routePriceNewSearchParam.setArrAreaCd(destination);
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        if (!StringUtils.isNull(materialType)) {
            if (materialType.equals("PH")) {
                routePriceNewSearchParam.setChargeAdjustType("volume");
            } else {
                routePriceNewSearchParam.setChargeAdjustType(chargeadjustType);
            }
        } else {
            routePriceNewSearchParam.setChargeAdjustType("*");
        }
        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            if (result != null && result.size() > 0) {
                return result;
            } else {
                routePriceNewSearchParam.setDptrAreaCd("*");
                routePriceNewSearchParam.setArrAreaCd("*");
                result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
                return result;
            }
        }

    }
    @Override
    public List<TFeeRoutePriceNewVo> findRoutepriceUseTariff(TFoFreightOrderItem freightOrderItem) {

        String custNo = freightOrderItem.getCustomerNo();
        String depart = freightOrderItem.getDeparture();
        String destination = freightOrderItem.getDestination();
        String materialType = freightOrderItem.getCargoFreightSpec();
        String isExpressYn = freightOrderItem.getIsHotYn();
        String chargeadjustType = freightOrderItem.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("LTL");
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd(depart);
        routePriceNewSearchParam.setArrAreaCd(destination);
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        if (!StringUtils.isNull(materialType)) {
            if (materialType.equals("PH")) {
                routePriceNewSearchParam.setChargeAdjustType("volume");
            } else {
                routePriceNewSearchParam.setChargeAdjustType(chargeadjustType);
            }
        } else {
            routePriceNewSearchParam.setChargeAdjustType("*");
        }
        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            if (result != null && result.size() > 0) {
                return result;
            } else {
                routePriceNewSearchParam.setDptrAreaCd("*");
                routePriceNewSearchParam.setArrAreaCd("*");
                result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
                return result;
            }
        }

    }
    @Override
    public List<TFeeRoutePriceNewVo> findFtlRoutepriceUseTariff(PurchaseOrder tFoFreightOrder) {

        String custNo = tFoFreightOrder.getCustomerNo();
        String depart = tFoFreightOrder.getDeparture();
        String destination = tFoFreightOrder.getDestination();


        String isExpressYn = tFoFreightOrder.getIsHotYn();
        String chargeadjustType = tFoFreightOrder.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("FTL");
        routePriceNewSearchParam.setVehicleModel(tFoFreightOrder.getRequestVehicleModel());
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd(depart);
        routePriceNewSearchParam.setArrAreaCd(destination);
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            return result;

        }

    }
    @Override
    public List<TFeeRoutePriceNewVo> findFtlRoutepriceUseTariff(TFoFreightOrder tFoFreightOrder) {

        String custNo = tFoFreightOrder.getCustomerNo();
        String depart = tFoFreightOrder.getDeparture();
        String destination = tFoFreightOrder.getDestination();


        String isExpressYn = tFoFreightOrder.getIsHotYn();
        String chargeadjustType = tFoFreightOrder.getSettledBasedOn();
        TFeeRoutePriceNewSearchParam routePriceNewSearchParam = new TFeeRoutePriceNewSearchParam();
        routePriceNewSearchParam.setApplyDt(DateUtils.formatDate(new Date(), "yyyyMMdd"));
        routePriceNewSearchParam.setSaleBuyType("1");
        routePriceNewSearchParam.setSurviceType("FTL");
        routePriceNewSearchParam.setVehicleModel(tFoFreightOrder.getVehicleModelNo());
        routePriceNewSearchParam.setCustCd(custNo);
        routePriceNewSearchParam.setDptrAreaCd(depart);
        routePriceNewSearchParam.setArrAreaCd(destination);
        routePriceNewSearchParam.setFrtCd("CountCarriage");

        List<TFeeRoutePriceNewVo> result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);

        if (result != null && result.size() > 0) {
            return result;
        } else {
            routePriceNewSearchParam.setCustCd("*");
            result = this.routePriceNewMapper.findAllPrice(routePriceNewSearchParam);
            return result;

        }

    }
    @Transactional(readOnly = false)
    @Override
    public Double getMileFromTwoLocations(TFoTransitRoute transitRoute){
        String getUrl = String.format(Locale.ROOT, lbsApiProperties.getGeoCodeGeoUrl(), lbsApiProperties.getKey(),
                transitRoute.getPickUpAdd(), transitRoute.getDropOffAdd());
        Optional<LbsApiResponseVo> lbsApiResponseVo = HttpClientUtils.get(getUrl, LbsApiResponseVo.class, false);
        if (lbsApiResponseVo.isPresent()
                && Constants.NUMBER_ONE_STR.equalsIgnoreCase(lbsApiResponseVo.get().getStatus())) {
            JSONArray geocodes = lbsApiResponseVo.get().getGeocodes();
            List<JSONObject> jeoArr = geocodes.toJavaList(JSONObject.class);
            transitRoute.setPickupLongitude(
                    new BigDecimal(jeoArr.get(0).getString(LOCATION).split(Constants.PATTERN_COMMA)[0]));
            transitRoute.setPickupLatitude(
                    new BigDecimal(jeoArr.get(0).getString(LOCATION).split(Constants.PATTERN_COMMA)[1]));
            transitRoute.setDeliveryLongitude(
                    new BigDecimal(jeoArr.get(1).getString(LOCATION).split(Constants.PATTERN_COMMA)[0]));
            transitRoute.setDeliveryLatitude(
                    new BigDecimal(jeoArr.get(1).getString(LOCATION).split(Constants.PATTERN_COMMA)[1]));
        } else {
            if (!lbsApiResponseVo.isPresent()) {
                log.error("get get location fail, param: {}", JSON.toJSONString(transitRoute));
            } else {
                log.error("get get location fail, param: {}, reason: {}", JSON.toJSONString(transitRoute),
                        lbsApiResponseVo.get().getInfo());
            }
        }
        Double mile = calculateDistanceMile(transitRoute);
      return mile;
    }
    private Double calculateDistanceMile(TFoTransitRoute transitRoute) {
        double lat1 = transitRoute.getPickupLatitude().doubleValue();
        double lat2 = transitRoute.getDeliveryLatitude().doubleValue();
        double lon1 = transitRoute.getPickupLongitude().doubleValue();
        double lon2 = transitRoute.getDeliveryLongitude().doubleValue();
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lon1) - rad(lon2);
        double c = 2 * EARTH_RADIUS * Math.asin(Math
                .sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        return Math.round(c * 10000d) / 10000d;
    }

    private double rad(double d) {
        return d * Math.PI / 180.0;
    }


    @Transactional(readOnly = false)
    @Override
    public String generateFreightOrderFromDelivery
            (TbWmsMaterialDeliverySaveParam params , List<TbWmsMaterialDeliveryLine> tbWmsMaterialDeliveryLines,
             TFoFreightOrder order, List<TFoFreightOrderItem> tFoFreightOrderItems) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        Double totAmt = 0.0;
        TbWmsMaterialDelivery tbWmsMaterialDeliveryVo = new TbWmsMaterialDelivery();
        TFoTransitRoute transitRoute = new TFoTransitRoute();
        Customer cust =  new Customer();
        TFoTransitRoute transitRouteentity = new TFoTransitRoute();
        TBmLocationVo location = new TBmLocationVo();;
        TBmLocationVo destlocation = new TBmLocationVo();
        String orderNo = "";
        for(int i=0;i<tbWmsMaterialDeliveryLines.size();i++){
            TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine
                    = (TbWmsMaterialDeliveryLine)tbWmsMaterialDeliveryLines.get(i);
            if(i==0){
                tbWmsMaterialDeliveryVo = this.tbWmsMaterialDeliveryMapper.selectById(tbWmsMaterialDeliveryLine.getDeliveryId());
                order.setCustomerName(tbWmsMaterialDeliveryLine.getCustomerName());
                 orderNo = tBmsAllGeneralSeqTabService.generateNo("freightOrder");
                order.setOrderNo("WMS".concat(orderNo));
                order.setCustomerNo(tbWmsMaterialDeliveryLine.getCustomerNo());
                order.setCompanyName(sysUser.getCompanyName());
                order.setCompanyNo(sysUser.getCustomerId());

                order.setConsigneeAddress(tbWmsMaterialDeliveryVo.getConsigneeAddress());
                // order.setConsigneeLinkMan(tbWmsMaterialDeliveryVo.get);
                order.setConsigneeMobilePhone(tbWmsMaterialDeliveryVo.getConsigneePhoneNo());
                order.setConsigneeNo(tbWmsMaterialDeliveryVo.getConsignee());
                Warehouse warehouse = this.warehouseMapper.
                        selectById(tbWmsMaterialDeliveryLine.getPickUpWarehouseNo());
                if(warehouse==null){
                    OrgVo thisOrg = this.orgMapper.findById(sysUser.getOrgId());
                    warehouse =this.warehouseMapper.
                            selectById(thisOrg.getWarehouseCode());
                }

                Warehouse deliverywarehouse = this.warehouseMapper.
                        selectById(tbWmsMaterialDeliveryLine.getDeliveryWarehouseCode());
                 cust = this.customerMapper.selectById(tbWmsMaterialDeliveryLine.getCustomerNo());
                order.setDepartmentNo(sysUser.getOrgId());
                if(deliverywarehouse.getCity()!=null&&deliverywarehouse.getProvince()!=null&&deliverywarehouse.getDistrict()!=null){
                    order.setDestination(deliverywarehouse.getProvince().concat(",").
                            concat(deliverywarehouse.getCity()).concat(",").concat(deliverywarehouse.getDistrict()));
                    order.setDestinationName(deliverywarehouse.getWarehouserName());
                }else if(cust.getLocationCode()!=null){
                    order.setDestination(cust.getLocationCode());
                    order.setDestinationName(cust.getDistrict());
                }
                if(warehouse.getCity()!=null&&warehouse.getProvince()!=null&&warehouse.getDistrict()!=null){
                    order.setDeparture(warehouse.getProvince().concat(",").
                            concat(warehouse.getCity()).concat(",").concat(warehouse.getDistrict()));
                    order.setDepartureName(warehouse.getDistrict());
                }

                 transitRoute =
                        this.tFoTransitRouteMapper.findByPickLocAndDestBySiteEntity(order.getDeparture(),order.getDestination(),sysUser.getOrgId());

                 location = this.tBmLocationMapper.findByTreeId(order.getDeparture());
                 destlocation = this.tBmLocationMapper.findByTreeId(order.getDestination());

                if(transitRoute!=null){
                    order.setDepartPortAddress(transitRoute.getPickUpAdd());
                    order.setDepartPort(warehouse.getWarehouseDesc());
                    order.setDestPortAddress(transitRoute.getDropOffAdd());
                    order.setEstDeliveryDays(transitRoute.getEstDeliveryDays());
                    if(transitRoute.getMilometer()==null){
                        Double mile = this.getMileFromTwoLocations(transitRoute);
                        transitRoute.setMilometer(new BigDecimal(mile));
                    }
                    Date eta = DateUtils.getDateAfter(DateUtils.parseDate(tbWmsMaterialDeliveryLine.getRequestDeliveryTime()),Integer.valueOf(transitRoute.getEstDeliveryDays()));
                    order.setShippingTime(eta);
                    order.setTransportationType(transitRoute.getRouteType());//铁路，公路，联运，船运
                }else{

                    transitRouteentity.setDepartDistributorSite(sysUser.getOrgId());
                    transitRouteentity.setPickUpAdd(warehouse.getAddress());

                    if(tbWmsMaterialDeliveryLine.getUnloadDockName()==null){
                        transitRouteentity.setDropOffAdd(deliverywarehouse.getWarehouserName());
                    }else{
                        transitRouteentity.setDropOffAdd(tbWmsMaterialDeliveryLine.getUnloadDockName());
                    }
                    transitRouteentity.setStartLocation(order.getDeparture());
                    transitRouteentity.setEndLocation(order.getDestination());
                    transitRouteentity.setDepartZone(location.getDepartZone());
                    transitRouteentity.setDestZone(destlocation.getDepartZone());
                    //  transitRouteentity.setMilometer();需要调用百度地图
                    if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getRequestDeliveryTime())){
                        double eta = DateUtils.getDistanceOfTwoDate(tbWmsMaterialDeliveryLine.getRequestDeliveryTime(),new Date());
                        transitRouteentity.setEstDeliveryDays(String.valueOf(eta));
                    }

                    transitRouteentity.preInsert(sysUser.getId());
                    tFoTransitRouteMapper.insert(transitRouteentity);
                    transitRoute = transitRouteentity;
                }

                order.setCarrierTime(tbWmsMaterialDeliveryVo.getPreDeliveryTime());


                order.setShipperName(cust.getCustomerName());
                order.setShipperPhone(cust.getContactPhone());
                order.setSourceOrderId(tbWmsMaterialDeliveryVo.getId());
                order.setSourceOrderNo(tbWmsMaterialDeliveryVo.getOrderNo());

                //     order.setServiceType(params.getServiceType());
                //    order.setVehicleModelNo(params.getVehicleModelNo());
                //    order.setOrderTypeNo(params.getOrderTypeNo()); //LTl ftl
                order.setOrderDate(new Date());
                order.setFreightOrderNo(orderNo);
                order.setDepartPort(warehouse.getId());
                order.setDestPort(deliverywarehouse.getId());
                order.setStatus("created");
                order.setShipperAddress(warehouse.getAddress());
                order.setConsigneeAddress(deliverywarehouse.getAddress());
                //     order.setVehicleModelNo(params.getVehicleModelNo());
                order.setId(idWorker.nextId() + "").preInsert(sysUser.getId());

                this.mapper.insert(order);
            }
            TFoFreightOrderItem tFoFreightOrderItem = new TFoFreightOrderItem();
            tFoFreightOrderItem.setCargoFreightNo(tbWmsMaterialDeliveryLine.getMaterialNo());
            tFoFreightOrderItem.setCargoFreightName(tbWmsMaterialDeliveryLine.getMaterialName());
            // 图号
            tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLine.getSkuCode());

            tFoFreightOrderItem.setShipByPackOrqty(tbWmsMaterialDeliveryLine.getShipByPackOrqty());
            if(tbWmsMaterialDeliveryLine.getCargoValue()!=null){
                tFoFreightOrderItem.setCargoValue
                        (BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getCargoValue()));

            }
            TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterialVo = null;
            Sku sku = null;
            int qtyPerPack = 0;
            BigDecimal unitWeight = new BigDecimal(1.0);
            BigDecimal unitVol =new BigDecimal(1.0);

            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getSkuCode())){
                tWhWarehouseCustomerMaterialVo=  this.tWhWarehouseCustomerMaterialMapper.findBySkuCode(tbWmsMaterialDeliveryLine.getSkuCode());
                if(tWhWarehouseCustomerMaterialVo!=null){
                     qtyPerPack = tWhWarehouseCustomerMaterialVo.getQtyPerPack();
                     unitWeight = tWhWarehouseCustomerMaterialVo.getUnitWeight();
                     unitVol = tWhWarehouseCustomerMaterialVo.getUnitVolume();
                    tFoFreightOrderItem.setCargoFreightSpec(tWhWarehouseCustomerMaterialVo.getSpec());
                }
            }else{
                tWhWarehouseCustomerMaterialVo=  this.tWhWarehouseCustomerMaterialMapper.selectById(tbWmsMaterialDeliveryLine.getMaterialNo());
                if(tWhWarehouseCustomerMaterialVo!=null){
                    qtyPerPack = tWhWarehouseCustomerMaterialVo.getQtyPerPack()==null?1:tWhWarehouseCustomerMaterialVo.getQtyPerPack();
                    unitWeight = tWhWarehouseCustomerMaterialVo.getUnitWeight()==null?new BigDecimal(1):tWhWarehouseCustomerMaterialVo.getUnitWeight();
                    unitVol = tWhWarehouseCustomerMaterialVo.getUnitVolume()==null?new BigDecimal(1):tWhWarehouseCustomerMaterialVo.getUnitVolume();
                    tFoFreightOrderItem.setCargoFreightSpec(tWhWarehouseCustomerMaterialVo.getSpec());
                }
            }


            tFoFreightOrderItem.setOrderFrNo(tbWmsMaterialDeliveryLine.getOrderNo());
            tFoFreightOrderItem.setConsigneeName(tbWmsMaterialDeliveryLine.getCustomerName());
            tFoFreightOrderItem.setConsignee(tbWmsMaterialDeliveryLine.getCustomerNo());
            tFoFreightOrderItem.setConsigneeAddress(tbWmsMaterialDeliveryLine.getConsigneeAddress());
            tFoFreightOrderItem.setConsigneeLinkman(cust.getContactName());
            tFoFreightOrderItem.setConsigneePhone(cust.getContactPhone());
            if(transitRoute.getMilometer()!=null){
                tFoFreightOrderItem.setMiles(transitRoute.getMilometer().longValue());

            }
            tFoFreightOrderItem.setDepartZone(transitRoute.getDepartZone());
            tFoFreightOrderItem.setDestZone(transitRoute.getDestZone());
            tFoFreightOrderItem.setConsigneeLinktype(cust.getCustomerType());
            tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLine.getSkuCode());
            //tFoFreightOrderItem.setConsigneeReceiveQuantity();
            tFoFreightOrderItem.setSettledBasedOn(tbWmsMaterialDeliveryLine.getShipByPackOrqty());
            if(tbWmsMaterialDeliveryLine.getShipByPackOrqty()!=null){
                if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("pack")){
                    tFoFreightOrderItem.setPacking(tbWmsMaterialDeliveryLine.getMeasUnitNo());
                    if(tbWmsMaterialDeliveryLine.getQuantity()!=null){
                        tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getQuantity()));
                        Double volume = NumberUtils.mul(tbWmsMaterialDeliveryLine.getQuantity(),unitVol.doubleValue());
                        tFoFreightOrderItem.setVolume(BigDecimal.valueOf(volume));
                        Double weight = NumberUtils.mul(tbWmsMaterialDeliveryLine.getQuantity(),unitWeight.doubleValue());
                        tFoFreightOrderItem.setWeight(BigDecimal.valueOf(weight));
                        if(!StringUtils.isNull(qtyPerPack)){
                            Double qty = NumberUtils.mul(tbWmsMaterialDeliveryLine.getQuantity(),qtyPerPack);
                            tFoFreightOrderItem.setQuantity(BigDecimal.valueOf(qty));
                        }else{
                            tFoFreightOrderItem.setQuantity
                                    (BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getQuantity()));
                        }
                    }

                    tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getPackQty());
                    tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getPackQty());
                }else if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("weight")){
                    tFoFreightOrderItem.setWeightMeasUnit(tbWmsMaterialDeliveryLine.getMeasUnitNo());
                    if(tbWmsMaterialDeliveryLine.getWeight()!=null){
                        tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getWeight()));
                        if(!StringUtils.isNull(qtyPerPack)){
                            Double pack = NumberUtils.div(tbWmsMaterialDeliveryLine.getWeight(),qtyPerPack);
                            tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                        }
                        tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getWeight());
                        tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getWeight());
                    }
                    if(tbWmsMaterialDeliveryLine.getQuantity()!=null){
                        tFoFreightOrderItem.setQuantity(BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getQuantity()));
                    }



                }else if(tbWmsMaterialDeliveryLine.getShipByPackOrqty().equals("vol")){
                    tFoFreightOrderItem.setVolumeMeasUnit(tbWmsMaterialDeliveryLine.getMeasUnitNo());
                    if(tbWmsMaterialDeliveryLine.getWeight()!=null){
                        tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getWeight()));
                    }

                    tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLine.getVolume());


                    if(!StringUtils.isNull(qtyPerPack)){
                        if(tbWmsMaterialDeliveryLine.getQuantity()!=null){
                            Double pack = NumberUtils.div(tbWmsMaterialDeliveryLine.getQuantity(),qtyPerPack);
                            tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                        }

                    }
                    tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getVolume());
                    tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getVolume());
                }else{
                    tFoFreightOrderItem.setMeasUnit(tbWmsMaterialDeliveryLine.getMeasUnitNo());
                    tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLine.getVolume());

                    tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLine.getWeight()));
                    tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getQuantity());
                    if(!StringUtils.isNull(qtyPerPack)){
                        Double pack = NumberUtils.div(tbWmsMaterialDeliveryLine.getQuantity(),qtyPerPack);
                        tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                    }
                    tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getQuantity());
                }
            }

            tFoFreightOrderItem.setPalletQty(tbWmsMaterialDeliveryLine.getPalletQty());
            tFoFreightOrderItem.setCompanyNo(sysUser.getCustomerId());
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLine.getRequestDeliveryTime())){
                Date esta = DateUtils.parseDate(tbWmsMaterialDeliveryLine.getRequestDeliveryTime());
                tFoFreightOrderItem.setEstDeliveryDate(esta);
            }

            tFoFreightOrderItem.setEstDepartTm(order.getCarrierTime());
            tFoFreightOrderItem.setDepartPort(order.getDepartPort());
            if(transitRoute!=null) {
                tFoFreightOrderItem.setDepartPortAddress(transitRoute.getPickUpAdd());
                tFoFreightOrderItem.setDestinationAddr(transitRoute.getDropOffAdd());
                tFoFreightOrderItem.setIsSelfRouteYn(transitRoute.getIsSelfRouteYn());
            }else{
                tFoFreightOrderItem.setDepartPortAddress(transitRouteentity.getPickUpAdd());
                tFoFreightOrderItem.setDestinationAddr(transitRouteentity.getDropOffAdd());
                tFoFreightOrderItem.setIsSelfRouteYn("0");
            }
            tFoFreightOrderItem.setDeparture(order.getDeparture());

            tFoFreightOrderItem.setFreightOrderNo(orderNo);
            tFoFreightOrderItem.setDestination(order.getDestination());
            tFoFreightOrderItem.setOrderFromSource("WMS");

            tFoFreightOrderItem.setStatus("created");
            tFoFreightOrderItem.setOrderTypeNo(order.getOrderTypeNo());
            String serviceType = "drayge" ;
            String depart = order.getDeparture().split(",")[1];
            String dest = order.getDestination().split(",")[1];
            if(!depart.equals(dest)){
                serviceType= "longHaul" ;
            }
            tFoFreightOrderItem.setServiceType(serviceType);
            tFoFreightOrderItem.setDeliveryType(order.getServiceType());
        /*    if(params.getOrderTypeNo().equals("FTL")){
                List<TFeeRoutePriceNewVo> routePriceNews = this.findFtlRoutepriceUseTariff(order);
                if (routePriceNews != null && routePriceNews.size() > 0) {
                    TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                    totAmt = routePriceNewVo.getBasicAmt().doubleValue();
                    tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
                } else {
                    routePriceNews = this.findFtlPerMileRoutepriceUseTariff(order);
                    if (routePriceNews != null && routePriceNews.size() > 0) {
                        TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                        Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                        totAmt = NumberUtils.mul(unitAmt, transitRoute.getMilometer().doubleValue());
                        tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
                    }
                }
            }else{

                List<TFeeRoutePriceNewVo>  routePriceNews = this.findRoutepriceUseTariff(tFoFreightOrderItem);
                if (routePriceNews != null && routePriceNews.size() > 0) {
                    TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                    Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                    totAmt = NumberUtils.mul(unitAmt,tFoFreightOrderItem.getCountQuantity().doubleValue() );
                    tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
                }
                // tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf());
            }*/

            tFoFreightOrderItem.setFreightOrderId(order.getId());
            tFoFreightOrderItem.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
            tFoFreightOrderItem.setDestination(order.getDestination());
            tFoFreightOrderItem.setDeparture(order.getDeparture());

            tFoFreightOrderItem.setDepartZone(location.getDepartZone());
            tFoFreightOrderItem.setDestZone(destlocation.getDepartZone());
            tFoFreightOrderItem.setDepartName(location.getTreeNames());
            tFoFreightOrderItem.setDestName(destlocation.getTreeNames());

            if(tFoFreightOrderItem.getSettledBasedOn()!=null){
                if(tFoFreightOrderItem.getSettledBasedOn().equals("件")
                        ||tFoFreightOrderItem.getSettledBasedOn().equals("包")||tFoFreightOrderItem.getSettledBasedOn().equals("箱")){
                    tFoFreightOrderItem.setSettledBasedOn("pack");
                    tFoFreightOrderItem.setShipByPackOrqty("pack");
                }else if(tFoFreightOrderItem.getSettledBasedOn().equals("个")
                        ||tFoFreightOrderItem.getSettledBasedOn().equals("只")){
                    tFoFreightOrderItem.setSettledBasedOn("个");
                    tFoFreightOrderItem.setShipByPackOrqty("个");
                }else if(tFoFreightOrderItem.getSettledBasedOn().equals("m3")
                        ||tFoFreightOrderItem.getSettledBasedOn().equals("立方")){
                    tFoFreightOrderItem.setSettledBasedOn("vol");
                    tFoFreightOrderItem.setShipByPackOrqty("vol");
                }else if(tFoFreightOrderItem.getSettledBasedOn().equals("吨")
                        ||tFoFreightOrderItem.getSettledBasedOn().equals("kg")
                        ||tFoFreightOrderItem.getSettledBasedOn().equals("t")){
                    tFoFreightOrderItem.setSettledBasedOn("weight");
                    tFoFreightOrderItem.setShipByPackOrqty("weight");
                }
            }
            tFoFreightOrderItem.setDepartureAddr(order.getShipperAddress());
            tFoFreightOrderItem.setConsigneeAddress(order.getConsigneeAddress());
            tFoFreightOrderItem.setSite(sysUser.getOrgId());
            this.tFoFreightOrderItemMapper.insert(tFoFreightOrderItem);
            tFoFreightOrderItems.add(tFoFreightOrderItem);
            tbWmsMaterialDeliveryLine.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            tbWmsMaterialDeliveryLine.setFreightOrderNo(tFoFreightOrderItem.getFreightOrderNo());
            tbWmsMaterialDeliveryLine.preUpdate(sysUser.getId());
            this.tbWmsMaterialDeliveryLineMapper.updateById(tbWmsMaterialDeliveryLine);

        }
        return "success";
    }
    @Transactional(readOnly = false)
    @Override
    public String generateFreightOrderFromDelivery
            (TFoFreightOrderSaveParam params , TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo,
             TbWmsMaterialDeliveryVo tbWmsMaterialDeliveryVo, TFoFreightOrder order, TFoFreightOrderItem tFoFreightOrderItem) {

        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

        Double totAmt = 0.0;
        if(params.getOrderTypeNo()==null||params.getOrderTypeNo()==""){
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseType())){
                if(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseType().equals("总装"))
                { //某个地方  拉动的时候要设立这个值
                    params.setOrderTypeNo("FTL");
                }else{
                    params.setOrderTypeNo("LTL");
                }
            }else{
                params.setOrderTypeNo("LTL");
            }

        }


        order.setCustomerName(tbWmsMaterialDeliveryLineVo.getCustomerName());
        String orderNo = tBmsAllGeneralSeqTabService.generateNo("freightOrder");
        order.setOrderNo("WMS".concat(orderNo));
        order.setCustomerNo(tbWmsMaterialDeliveryLineVo.getCustomerNo());
        order.setCompanyName(sysUser.getCompanyName());
        order.setCompanyNo(sysUser.getCustomerId());

        order.setConsigneeAddress(tbWmsMaterialDeliveryVo.getConsigneeAddress());
        // order.setConsigneeLinkMan(tbWmsMaterialDeliveryVo.get);
        order.setConsigneeMobilePhone(tbWmsMaterialDeliveryVo.getConsigneePhoneNo());
        order.setConsigneeNo(tbWmsMaterialDeliveryVo.getConsignee());
        Warehouse warehouse = this.warehouseMapper.
                findByCode(tbWmsMaterialDeliveryVo.getWarehouseCode());
        if(warehouse==null){
            OrgVo thisOrg = this.orgMapper.findById(sysUser.getOrgId());
            warehouse =this.warehouseMapper.
                    findByCode(thisOrg.getWarehouseCode());
        }

        Warehouse deliverywarehouse = this.warehouseMapper.
                findByCode(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseCode());
        Customer cust = this.customerMapper.selectById(tbWmsMaterialDeliveryLineVo.getCustomerNo());
        order.setDepartmentNo(sysUser.getOrgId());
        if(deliverywarehouse.getCity()!=null&&deliverywarehouse.getProvince()!=null&&deliverywarehouse.getDistrict()!=null){
            order.setDestination(deliverywarehouse.getProvince().concat(",").
                    concat(deliverywarehouse.getCity()).concat(",").concat(deliverywarehouse.getDistrict()));
            order.setDestinationName(deliverywarehouse.getWarehouserName());
        }else if(cust.getLocationCode()!=null){
            order.setDestination(cust.getLocationCode());
            order.setDestinationName(cust.getDistrict());
        }
        if(warehouse.getCity()!=null&&warehouse.getProvince()!=null&&warehouse.getDistrict()!=null){
            order.setDeparture(warehouse.getProvince().concat(",").
                    concat(warehouse.getCity()).concat(",").concat(warehouse.getDistrict()));
            order.setDepartureName(warehouse.getDistrict());
        }

        TFoTransitRoute transitRoute =
                this.tFoTransitRouteMapper.findByPickLocAndDestBySiteEntity(order.getDeparture(),order.getDestination(),sysUser.getOrgId());
        TFoTransitRoute transitRouteentity = new TFoTransitRoute();
        TBmLocationVo location = this.tBmLocationMapper.findByTreeId(order.getDeparture());
        TBmLocationVo destlocation = this.tBmLocationMapper.findByTreeId(order.getDestination());

        if(transitRoute!=null){
            order.setDepartPortAddress(transitRoute.getPickUpAdd());
            order.setDepartPort(warehouse.getWarehouseDesc());
            order.setDestPortAddress(transitRoute.getDropOffAdd());
            order.setEstDeliveryDays(transitRoute.getEstDeliveryDays());
            if(transitRoute.getMilometer()==null){
                Double mile = this.getMileFromTwoLocations(transitRoute);
                transitRoute.setMilometer(new BigDecimal(mile));
            }
            Date eta = DateUtils.getDateAfter(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()),Integer.valueOf(transitRoute.getEstDeliveryDays()));
            order.setShippingTime(eta);
            order.setTransportationType(transitRoute.getRouteType());//铁路，公路，联运，船运
        }else{
            transitRouteentity.setDepartDistributorSite(sysUser.getOrgId());
            transitRouteentity.setPickUpAdd(warehouse.getAddress());
            if(tbWmsMaterialDeliveryLineVo.getUnloadDockName() ==null){
                transitRouteentity.setDropOffAdd(order.getDestinationName());
            }else{
                transitRouteentity.setDropOffAdd(tbWmsMaterialDeliveryLineVo.getUnloadDockName());
            }
            transitRouteentity.setStartLocation(order.getDeparture());
            transitRouteentity.setEndLocation(order.getDestination());
            transitRouteentity.setDepartZone(location.getDepartZone());
            transitRouteentity.setDestZone(destlocation.getDepartZone());
            //  transitRouteentity.setMilometer();需要调用百度地图
            if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
                double eta = DateUtils.getDistanceOfTwoDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()),new Date());
                transitRouteentity.setEstDeliveryDays(String.valueOf(eta));
            }

            transitRouteentity.preInsert(sysUser.getId());
            tFoTransitRouteMapper.insert(transitRouteentity);
            transitRoute = transitRouteentity;
        }

        order.setCarrierTime(tbWmsMaterialDeliveryVo.getPreDeliveryTime());

        order.setShipperAddress(cust.getAddress());
        order.setShipperName(cust.getCustomerName());
        order.setShipperPhone(cust.getContactPhone());
        order.setIsHotYn(params.getIsHotYn());
        order.setInsureYn(params.getInsureYn());
        order.setSourceOrderId(tbWmsMaterialDeliveryVo.getId());
        order.setSourceOrderNo(tbWmsMaterialDeliveryVo.getOrderNo());

        order.setServiceType(params.getServiceType());
        order.setVehicleModelNo(params.getVehicleModelNo());
        order.setOrderTypeNo(params.getOrderTypeNo()); //LTl ftl
        order.setOrderDate(new Date());
        order.setFreightOrderNo(orderNo);
        order.setStatus("created");
        order.setVehicleModelNo(params.getVehicleModelNo());
        order.setId(idWorker.nextId() + "").preInsert(sysUser.getId());

        this.mapper.insert(order);
        //   TFoFreightOrderItem tFoFreightOrderItem = new TFoFreightOrderItem();
        tFoFreightOrderItem.setCargoFreightNo(tbWmsMaterialDeliveryLineVo.getMaterialNo());
        tFoFreightOrderItem.setCargoFreightName(tbWmsMaterialDeliveryLineVo.getMaterialName());
        // 图号
        tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());

        tFoFreightOrderItem.setShipByPackOrqty(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty());
        if(tbWmsMaterialDeliveryLineVo.getCargoValue()!=null){
            tFoFreightOrderItem.setCargoValue
                    (BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getCargoValue()));

        }
        TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterialVo =
                this.tWhWarehouseCustomerMaterialMapper.findBySkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
        int qtyPerPack = tWhWarehouseCustomerMaterialVo.getQtyPerPack();
        BigDecimal unitWeight = tWhWarehouseCustomerMaterialVo.getUnitWeight();
        BigDecimal unitVol = tWhWarehouseCustomerMaterialVo.getUnitVolume();
        tFoFreightOrderItem.setCargoFreightSpec(tWhWarehouseCustomerMaterialVo.getSpec());
        tFoFreightOrderItem.setOrderFrNo(tbWmsMaterialDeliveryLineVo.getOrderNo());
        tFoFreightOrderItem.setConsigneeName(tbWmsMaterialDeliveryLineVo.getCustomerName());
        tFoFreightOrderItem.setConsignee(tbWmsMaterialDeliveryLineVo.getCustomerNo());
        tFoFreightOrderItem.setConsigneeAddress(tbWmsMaterialDeliveryLineVo.getConsigneeAddress());
        tFoFreightOrderItem.setConsigneeLinkman(cust.getContactName());
        tFoFreightOrderItem.setConsigneePhone(cust.getContactPhone());
        if(transitRoute.getMilometer()!=null){
            tFoFreightOrderItem.setMiles(transitRoute.getMilometer().longValue());

        }
        tFoFreightOrderItem.setDepartZone(transitRoute.getDepartZone());
        tFoFreightOrderItem.setDestZone(transitRoute.getDestZone());
        tFoFreightOrderItem.setConsigneeLinktype(cust.getCustomerType());
        tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
        //tFoFreightOrderItem.setConsigneeReceiveQuantity();
        tFoFreightOrderItem.setSettledBasedOn(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty());
        if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty()!=null){
            if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("pack")){
                tFoFreightOrderItem.setPacking(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));

                Double volume = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),unitVol.doubleValue());
                tFoFreightOrderItem.setVolume(BigDecimal.valueOf(volume));

                Double weight = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),unitWeight.doubleValue());
                tFoFreightOrderItem.setWeight(BigDecimal.valueOf(weight));

                if(!StringUtils.isNull(qtyPerPack)){
                    Double qty = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                    tFoFreightOrderItem.setQuantity(BigDecimal.valueOf(qty));
                }else{
                    tFoFreightOrderItem.setQuantity
                            (BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
                }
                tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getPackQty());
                tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getPackQty());
            }else if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("weight")){
                tFoFreightOrderItem.setWeightMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));
                tFoFreightOrderItem.setQuantity(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
                if(!StringUtils.isNull(qtyPerPack)){
                    Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getWeight(),qtyPerPack);
                    tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                }
                tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getWeight());
                tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getWeight());
            }else if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("vol")){
                tFoFreightOrderItem.setVolumeMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLineVo.getVolume());
                tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));

                if(!StringUtils.isNull(qtyPerPack)){
                    if(tbWmsMaterialDeliveryLineVo.getQuantity()!=null){
                        Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                        tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                    }

                }
                tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getVolume());
                tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getVolume());
            }else{
                tFoFreightOrderItem.setMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLineVo.getVolume());
                tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));
                tFoFreightOrderItem.setRemainedQuantity(tFoFreightOrderItem.getQuantity());
                if(!StringUtils.isNull(qtyPerPack)){
                    Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                    tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                }
                tFoFreightOrderItem.setCountQuantity(tFoFreightOrderItem.getQuantity());
            }
        }

        tFoFreightOrderItem.setPalletQty(tbWmsMaterialDeliveryLineVo.getPalletQty());
        tFoFreightOrderItem.setCompanyNo(sysUser.getCustomerId());
        if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
            Date esta = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime());
            tFoFreightOrderItem.setEstDeliveryDate(esta);
        }

        tFoFreightOrderItem.setEstDepartTm(order.getCarrierTime());
        tFoFreightOrderItem.setDepartPort(order.getDepartPort());
        if(transitRoute!=null) {
            tFoFreightOrderItem.setDepartPortAddress(transitRoute.getPickUpAdd());
            tFoFreightOrderItem.setDestinationAddr(transitRoute.getDropOffAdd());
            tFoFreightOrderItem.setIsSelfRouteYn(transitRoute.getIsSelfRouteYn());
        }else{
            tFoFreightOrderItem.setDepartPortAddress(transitRouteentity.getPickUpAdd());
            tFoFreightOrderItem.setDestinationAddr(transitRouteentity.getDropOffAdd());
            tFoFreightOrderItem.setIsSelfRouteYn("0");
        }
        tFoFreightOrderItem.setDeparture(order.getDeparture());
        tFoFreightOrderItem.setDepartureAddr(order.getDepartPortAddress());
        tFoFreightOrderItem.setFreightOrderNo(orderNo);
        tFoFreightOrderItem.setDestination(order.getDestination());

        tFoFreightOrderItem.setOrderFromSource("WMS");

        tFoFreightOrderItem.setStatus("created");
        tFoFreightOrderItem.setOrderTypeNo(order.getOrderTypeNo());
        String serviceType = "drayge" ;
        String depart = order.getDeparture().split(",")[1];
        String dest = order.getDestination().split(",")[1];
        if(!depart.equals(dest)){
            serviceType= "longHaul" ;
        }
        tFoFreightOrderItem.setServiceType(serviceType);
        tFoFreightOrderItem.setDeliveryType(order.getServiceType());
        if(params.getOrderTypeNo().equals("FTL")){
            List<TFeeRoutePriceNewVo> routePriceNews = this.findFtlRoutepriceUseTariff(order);
            if (routePriceNews != null && routePriceNews.size() > 0) {
                TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                totAmt = routePriceNewVo.getBasicAmt().doubleValue();
                tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
            } else {
                routePriceNews = this.findFtlPerMileRoutepriceUseTariff(order);
                if (routePriceNews != null && routePriceNews.size() > 0) {
                    TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                    Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                    totAmt = NumberUtils.mul(unitAmt, transitRoute.getMilometer().doubleValue());
                    tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
                }
            }
        }else{

            List<TFeeRoutePriceNewVo>  routePriceNews = this.findRoutepriceUseTariff(tFoFreightOrderItem);
            if (routePriceNews != null && routePriceNews.size() > 0) {
                TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                totAmt = NumberUtils.mul(unitAmt,tFoFreightOrderItem.getCountQuantity().doubleValue() );
                tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf(totAmt));
            }
            // tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf());
        }

        tFoFreightOrderItem.setFreightOrderId(order.getId());
        tFoFreightOrderItem.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
        tFoFreightOrderItem.setDestination(order.getDestination());
        tFoFreightOrderItem.setDeparture(order.getDeparture());

        tFoFreightOrderItem.setDepartZone(location.getDepartZone());
        tFoFreightOrderItem.setDestZone(destlocation.getDepartZone());
        tFoFreightOrderItem.setDepartName(location.getTreeNames());
        tFoFreightOrderItem.setDestName(destlocation.getTreeNames());

        if(tFoFreightOrderItem.getSettledBasedOn()!=null){
            if(tFoFreightOrderItem.getSettledBasedOn().equals("件")
                    ||tFoFreightOrderItem.getSettledBasedOn().equals("包")||tFoFreightOrderItem.getSettledBasedOn().equals("箱")){
                tFoFreightOrderItem.setSettledBasedOn("pack");
                tFoFreightOrderItem.setShipByPackOrqty("pack");
            }else if(tFoFreightOrderItem.getSettledBasedOn().equals("个")
                    ||tFoFreightOrderItem.getSettledBasedOn().equals("只")){
                tFoFreightOrderItem.setSettledBasedOn("个");
                tFoFreightOrderItem.setShipByPackOrqty("个");
            }else if(tFoFreightOrderItem.getSettledBasedOn().equals("m3")
                    ||tFoFreightOrderItem.getSettledBasedOn().equals("立方")){
                tFoFreightOrderItem.setSettledBasedOn("vol");
                tFoFreightOrderItem.setShipByPackOrqty("vol");
            }else if(tFoFreightOrderItem.getSettledBasedOn().equals("吨")
                    ||tFoFreightOrderItem.getSettledBasedOn().equals("kg")
                    ||tFoFreightOrderItem.getSettledBasedOn().equals("t")){
                tFoFreightOrderItem.setSettledBasedOn("weight");
                tFoFreightOrderItem.setShipByPackOrqty("weight");
            }
        }
        tFoFreightOrderItem.setSite(sysUser.getOrgId());
        this.tFoFreightOrderItemMapper.insert(tFoFreightOrderItem);

        TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine =
                this.tbWmsMaterialDeliveryLineMapper.selectById(tbWmsMaterialDeliveryLineVo.getId());
        tbWmsMaterialDeliveryLine.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
        tbWmsMaterialDeliveryLine.setFreightOrderNo(tFoFreightOrderItem.getFreightOrderNo());
        tbWmsMaterialDeliveryLine.preUpdate(sysUser.getId());
        this.tbWmsMaterialDeliveryLineMapper.updateById(tbWmsMaterialDeliveryLine);

        return "success";

    }



    @Transactional(readOnly = false)
    @Override
    public String generateFreightOrderFromDelivery(TFoFreightOrderSaveParam params,
                               TbWmsMaterialDeliveryLineVo tbWmsMaterialDeliveryLineVo,
                                TbWmsMaterialDeliveryVo tbWmsMaterialDeliveryVo , PurchaseOrder order, PurchaseOrderItem tFoFreightOrderItem) {
        UserVo sysUser = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();

            Double totAmt = 0.0;
            if(params.getOrderTypeNo()==null||params.getOrderTypeNo()==""){
                if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseType())){
                    if(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseType().equals("总装"))
                    { //某个地方  拉动的时候要设立这个值
                        params.setOrderTypeNo("FTL");
                    }else{
                        params.setOrderTypeNo("LTL");
                    }
                }else{
                    params.setOrderTypeNo("FTL");
                }

            }


            order.setCompanyName(tbWmsMaterialDeliveryLineVo.getCustomerName());
            String orderNo = tBmsAllGeneralSeqTabService.generateNo("purchaseOrder");
            order.setPurchaseOrderNo("WMS".concat(orderNo));
            order.setCustomerNo(tbWmsMaterialDeliveryLineVo.getCustomerNo());

            order.setCarrierNo(params.getCarrier());
            order.setDeliveryAddress(tbWmsMaterialDeliveryVo.getConsigneeAddress());
            order.setConsigneeId(tbWmsMaterialDeliveryVo.getConsignee());
            order.setConsigneePhone(tbWmsMaterialDeliveryVo.getConsigneePhoneNo());

            Warehouse warehouse = this.warehouseMapper.
                selectById(tbWmsMaterialDeliveryVo.getWarehouseCode());
           if(warehouse==null){
               OrgVo thisOrg = this.orgMapper.findById(sysUser.getOrgId());
                warehouse =this.warehouseMapper.
                        selectById(thisOrg.getWarehouseCode());
            }

            Warehouse deliverywarehouse = this.warehouseMapper.
                    selectById(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseCode());
            Customer cust = this.customerMapper.selectById(tbWmsMaterialDeliveryLineVo.getCustomerNo());

            if(deliverywarehouse.getCity()!=null&&deliverywarehouse.getProvince()!=null&&deliverywarehouse.getDistrict()!=null){
                order.setDestination(deliverywarehouse.getProvince().concat(",").
                        concat(deliverywarehouse.getCity()).concat(",").concat(deliverywarehouse.getDistrict()));
                order.setDestinationName(deliverywarehouse.getWarehouserName());
                order.setDeliveryCity(order.getDestination());
            }else if(cust.getLocationCode()!=null){
                order.setDestination(cust.getLocationCode());
                order.setDestinationName(cust.getDistrict());
                order.setDeliveryCity(order.getDestination());
            }
            if(warehouse.getCity()!=null&&warehouse.getProvince()!=null&&warehouse.getDistrict()!=null){
                order.setDeparture(warehouse.getProvince().concat(",").
                        concat(warehouse.getCity()).concat(",").concat(warehouse.getDistrict()));
                order.setDepartureName(warehouse.getWarehouserName());
                order.setDepartCity(order.getDeparture());
            }

        if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
            Date delivgeryddate = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime());
            order.setExpectReceiptDate(delivgeryddate);
        }

        if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime())){
            Date pickup = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime());
            order.setPickupStartDate(pickup);
        }
           TFoTransitRoute transitRoute =
                   this.tFoTransitRouteMapper.findByPickLocAndDestBySiteEntity(order.getDeparture(),order.getDestination(),sysUser.getOrgId());
            TFoTransitRoute transitRouteentity = new TFoTransitRoute();
            TBmLocationVo location = this.tBmLocationMapper.findByTreeId(order.getDeparture());
            TBmLocationVo destlocation = this.tBmLocationMapper.findByTreeId(order.getDestination());

           if(transitRoute!=null){
               order.setPickUpAddress(transitRoute.getPickUpAdd());
               order.setDeparture(warehouse.getWarehouseDesc());
               order.setDestination(transitRoute.getDropOffAdd());
               if(!StringUtils.isNull(transitRoute.getEstDeliveryDays())){
                   order.setEstDeliveryDays(Integer.valueOf(transitRoute.getEstDeliveryDays()));
               }
               if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
                   Date delivgeryddate = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime());
                   order.setExpectReceiptDate(delivgeryddate);
               }

               if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime())){
                   Date pickup = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime());
                   order.setPickupStartDate(pickup);
               }
               if(transitRoute.getMilometer()==null){
                    Double mile = this.getMileFromTwoLocations(transitRoute);
                   transitRoute.setMilometer(new BigDecimal(mile));
               }

               order.setFreightTransportType(transitRoute.getRouteType());//铁路，公路，联运，船运
           }else{
               transitRouteentity.setRouteName(location.getLocationName().concat("-").concat(destlocation.getLocationName()));
               transitRouteentity.setDepartDistributorSite(sysUser.getOrgId());
               transitRouteentity.setPickUpAdd(warehouse.getAddress());
               transitRouteentity.setDropOffAdd(tbWmsMaterialDeliveryLineVo.getUnloadDockName());
               transitRouteentity.setStartLocation(order.getDeparture());
               transitRouteentity.setEndLocation(order.getDestination());
               transitRouteentity.setDepartZone(location.getDepartZone());
               transitRouteentity.setDestZone(destlocation.getDepartZone());
             //  transitRouteentity.setMilometer();需要调用百度地图
               if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
                   double eta = DateUtils.getDistanceOfTwoDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()),new Date());
                   transitRouteentity.setEstDeliveryDays(String.valueOf(eta));
               }
               if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
                   Date delivgeryddate = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime());
                   order.setExpectReceiptDate(delivgeryddate);
               }

               if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime())){
                   Date pickup = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime());
                   order.setPickupStartDate(pickup);
               }

               transitRouteentity.preInsert(sysUser.getId());
               tFoTransitRouteMapper.insert(transitRouteentity);
               transitRoute = transitRouteentity;
           }


            order.setPickUpAddress(cust.getAddress());
            order.setCompanyName(cust.getCustomerName());
            order.setPickupContactMobile(cust.getContactPhone());
            order.setIsHotYn(params.getIsHotYn());
            order.setInsureYn(params.getInsureYn());
            order.setSourceOrderId(tbWmsMaterialDeliveryVo.getOrderNo());


            order.setFreightServiceType(params.getServiceType());

            order.setFreightOrderTypeNo(params.getOrderTypeNo()); //LTl ftl
            order.setSite(params.getCarrier());
            order.setPurchaseOrderNo("P".concat(orderNo));
            order.setStatus("planning");
            order.setRequestVehicleModel(params.getVehicleModelNo());
            order.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
            order.setDropOffWarehouseNo(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseCode());
            order.setPickUpWarehouseNo(tbWmsMaterialDeliveryLineVo.getPickUpWarehouseNo());
            order.setTransitWarehouseNo(params.getTransitWarehouseNo());
    //        this.purchaseOrderMapper.insert(order);
         //   TFoFreightOrderItem tFoFreightOrderItem = new TFoFreightOrderItem();
            BeanUtils.copyProperties(tbWmsMaterialDeliveryLineVo,tFoFreightOrderItem);
            tFoFreightOrderItem.setMaterialNo(tbWmsMaterialDeliveryLineVo.getMaterialNo());
            tFoFreightOrderItem.setMaterialId(tbWmsMaterialDeliveryLineVo.getMaterialNo());
            tFoFreightOrderItem.setMaterialDesc(tbWmsMaterialDeliveryLineVo.getMaterialName());
            tFoFreightOrderItem.setMaterialDescribe(tbWmsMaterialDeliveryLineVo.getMaterialName());
             // 图号
            tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
            if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty()!=null){
                tFoFreightOrderItem.setShipbyQtyWeightOrPack(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty());
           }else{
                tFoFreightOrderItem.setShipbyQtyWeightOrPack("qty");
            }

            if(tbWmsMaterialDeliveryLineVo.getCargoValue()!=null){
                tFoFreightOrderItem.setValueAddedTax(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getCargoValue()));

            }
            TWhWarehouseCustomerMaterial tWhWarehouseCustomerMaterialVo =
                    this.tWhWarehouseCustomerMaterialMapper.findBySkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
             Integer qtyPerPack = null;
        BigDecimal unitWeight = new BigDecimal(0.0);
        BigDecimal unitVol = new BigDecimal(0.0);
             if(tWhWarehouseCustomerMaterialVo!=null){
                 if(tWhWarehouseCustomerMaterialVo.getQtyPerPack()!=null){
                     qtyPerPack = tWhWarehouseCustomerMaterialVo.getQtyPerPack();
                 }

                  unitWeight = tWhWarehouseCustomerMaterialVo.getUnitWeight();
                  unitVol = tWhWarehouseCustomerMaterialVo.getUnitVolume();
                 tFoFreightOrderItem.setSpec(tWhWarehouseCustomerMaterialVo.getSpec());
             }



            if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
             //   Date eta = DateUtils.getDateAfter(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()),Double.valueOf(transitRoute.getEstDeliveryDays()).intValue());
             //   tFoFreightOrderItem.setEstDeliveryTime(eta);
                tFoFreightOrderItem.setEstDeliveryTime(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()));
            }
           if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime())){

            tFoFreightOrderItem.setEstPickUpTime(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime()));
           }



            tFoFreightOrderItem.setCustomerName(tbWmsMaterialDeliveryLineVo.getCustomerName());
            tFoFreightOrderItem.setConsigneeId(tbWmsMaterialDeliveryLineVo.getCustomerNo());
            tFoFreightOrderItem.setDeliveryAddress(tbWmsMaterialDeliveryLineVo.getConsigneeAddress());
            tFoFreightOrderItem.setContactName(cust.getContactName());
            tFoFreightOrderItem.setConsigneePhone(cust.getContactPhone());
            if(transitRoute.getMilometer()!=null){
                tFoFreightOrderItem.setMiles(transitRoute.getMilometer().doubleValue());

            }

            tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());
            //tFoFreightOrderItem.setConsigneeReceiveQuantity();
            tFoFreightOrderItem.setShipbyQtyWeightOrPack(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty());
            if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty()!=null){
                if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("pack")){
                    tFoFreightOrderItem.setPacking(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                    tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));

                    Double volume = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),unitVol.doubleValue());
                    tFoFreightOrderItem.setVolume(BigDecimal.valueOf(volume));

                    Double weight = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),unitWeight.doubleValue());
                    tFoFreightOrderItem.setWeight(BigDecimal.valueOf(weight));

                    if(!StringUtils.isNull(qtyPerPack)){
                        Double qty = NumberUtils.mul(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                        tFoFreightOrderItem.setSalesQuantity(BigDecimal.valueOf(qty));
                    }else{
                        tFoFreightOrderItem.setSalesQuantity(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
                    }
                    tFoFreightOrderItem.setRemainQuantity(tFoFreightOrderItem.getPackQty());
                    tFoFreightOrderItem.setPackQty(tFoFreightOrderItem.getPackQty());
                    tFoFreightOrderItem.setOrderQuantity(tFoFreightOrderItem.getPackQty());
                }else if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("weight")){
                    tFoFreightOrderItem.setWeightMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                    if(tbWmsMaterialDeliveryLineVo.getWeight()!=null){
                        tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));
                    }else{
                        tFoFreightOrderItem.setWeight(new BigDecimal(1.0));
                    }

                    if(tbWmsMaterialDeliveryLineVo.getQuantity()!=null){
                          tFoFreightOrderItem.setOrderQuantity(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
                    }else{
                        tFoFreightOrderItem.setWeight(new BigDecimal(1.0));
                    }


                    if(!StringUtils.isNull(qtyPerPack)){
                        Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getWeight(),qtyPerPack);
                        tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                    }
                    tFoFreightOrderItem.setRemainQuantity(tFoFreightOrderItem.getWeight());
                    tFoFreightOrderItem.setOrderQuantity(tFoFreightOrderItem.getWeight());

                }else if(tbWmsMaterialDeliveryLineVo.getShipByPackOrqty().equals("vol")){
                    tFoFreightOrderItem.setVolumeMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());



                    tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLineVo.getVolume());

                    if(tbWmsMaterialDeliveryLineVo.getWeight()!=null){
                        tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));
                    }else{
                        tFoFreightOrderItem.setWeight(new BigDecimal(1.0));
                    }



                    if(!StringUtils.isNull(qtyPerPack)){
                        if(tbWmsMaterialDeliveryLineVo.getQuantity()!=null){
                            Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                            tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                        }

                    }
                    tFoFreightOrderItem.setRemainQuantity(tFoFreightOrderItem.getVolume());
                    tFoFreightOrderItem.setOrderQuantity(tFoFreightOrderItem.getVolume());
                }else{
                    tFoFreightOrderItem.setMeasUnit(tbWmsMaterialDeliveryLineVo.getMeasUnitNo());
                    tFoFreightOrderItem.setVolume(tbWmsMaterialDeliveryLineVo.getVolume());
                    tFoFreightOrderItem.setWeight(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getWeight()));

                    if(!StringUtils.isNull(qtyPerPack)){
                        Double pack = NumberUtils.div(tbWmsMaterialDeliveryLineVo.getQuantity(),qtyPerPack);
                        tFoFreightOrderItem.setPackQty(BigDecimal.valueOf(pack));
                    }

                    if(tFoFreightOrderItem.getOrderQuantity()==null){
                        tFoFreightOrderItem.setRemainQuantity(BigDecimal.valueOf(tbWmsMaterialDeliveryLineVo.getQuantity()));
                    }else{
                        tFoFreightOrderItem.setRemainQuantity(tFoFreightOrderItem.getOrderQuantity());

                    }


                    tFoFreightOrderItem.setOrderQuantity(tFoFreightOrderItem.getVolume());
                }
            }


            if(!StringUtils.isNull(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime())){
                Date esta = DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime());
                tFoFreightOrderItem.setEstDeliveryTime(esta);
            }
            tFoFreightOrderItem.setPickUpAddress(order.getPickUpAddress());
            tFoFreightOrderItem.setEstPickUpTime(order.getPickupStartDate());
            tFoFreightOrderItem.setEstDeliveryTime(order.getExpectReceiptDate());

            if(transitRoute!=null) {
                tFoFreightOrderItem.setPickUpAddress(transitRoute.getPickUpAdd());
                tFoFreightOrderItem.setDeliveryAddress(transitRoute.getDropOffAdd());
                tFoFreightOrderItem.setIsSelfRouteYn(transitRoute.getIsSelfRouteYn());
            }else{
                tFoFreightOrderItem.setPickUpAddress(transitRouteentity.getPickUpAdd());
                tFoFreightOrderItem.setDeliveryAddress(transitRouteentity.getDropOffAdd());
                tFoFreightOrderItem.setIsSelfRouteYn("0");
            }
            tFoFreightOrderItem.setDeparture(order.getDeparture());
            tFoFreightOrderItem.setDeliveryAddress(order.getPickUpAddress());
            tFoFreightOrderItem.setPurchaseOrderNo(orderNo);
            tFoFreightOrderItem.setDestination(order.getDestination());
            tFoFreightOrderItem.setSkuCode(tbWmsMaterialDeliveryLineVo.getSkuCode());

            tFoFreightOrderItem.setOrderSource(tbWmsMaterialDeliveryLineVo.getOrderNo());
            tFoFreightOrderItem.setStatus("planning");
            tFoFreightOrderItem.setFreightOrderTypeNo(order.getFreightOrderTypeNo());
            String serviceType = "drayge" ;
            String depart = order.getDeparture().split(",")[1];
            String dest = order.getDestination().split(",")[1];
            if(!depart.equals(dest)){
                serviceType= "longHaul" ;
            }
            tFoFreightOrderItem.setServiceType(serviceType);
            tFoFreightOrderItem.setDeliveryType(order.getFreightServiceType());
            if(params.getOrderTypeNo().equals("FTL")){
                List<TFeeRoutePriceNewVo> routePriceNews = this.findFtlRoutepriceUseTariff(order);
                 if (routePriceNews != null && routePriceNews.size() > 0) {
                    TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                    totAmt = routePriceNewVo.getBasicAmt().doubleValue();
                     tFoFreightOrderItem.setAccountSum(BigDecimal.valueOf(totAmt));
                 } else {
                    routePriceNews = this.findFtlPerMileRoutepriceUseTariff(order);
                     if (routePriceNews != null && routePriceNews.size() > 0) {
                         TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                         Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                         totAmt = NumberUtils.mul(unitAmt, transitRoute.getMilometer().doubleValue());
                         tFoFreightOrderItem.setAccountSum(BigDecimal.valueOf(totAmt));
                     }
                }
            }else{

                List<TFeeRoutePriceNewVo>  routePriceNews = this.findRoutepriceUseTariff(tFoFreightOrderItem);
                if (routePriceNews != null && routePriceNews.size() > 0) {
                    TFeeRoutePriceNewVo routePriceNewVo = (TFeeRoutePriceNewVo) routePriceNews.get(0);
                    Double unitAmt = routePriceNewVo.getBasicAmt().doubleValue();
                    totAmt = NumberUtils.mul(unitAmt,tFoFreightOrderItem.getOrderQuantity().doubleValue() );
                    tFoFreightOrderItem.setAccountSum(BigDecimal.valueOf(totAmt));
                }
               // tFoFreightOrderItem.setAmountExpense(BigDecimal.valueOf());
            }

            tFoFreightOrderItem.setPurchaseOrderId(order.getId());
            tFoFreightOrderItem.setId(idWorker.nextId() + "").preInsert(sysUser.getId());
            tFoFreightOrderItem.setDestination(order.getDestination());
            tFoFreightOrderItem.setDeparture(order.getDeparture());

            tFoFreightOrderItem.setDepartZone(location.getDepartZone());
            tFoFreightOrderItem.setDestZone(destlocation.getDepartZone());


            if(tFoFreightOrderItem.getShipbyQtyWeightOrPack()!=null){
                if(tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("件")
                        ||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("包")||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("箱")){
                    tFoFreightOrderItem.setShipbyQtyWeightOrPack("pack");

                }else if(tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("个")
                        ||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("只")){
                    tFoFreightOrderItem.setShipbyQtyWeightOrPack("个");

                }else if(tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("m3")
                        ||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("立方")){
                    tFoFreightOrderItem.setShipbyQtyWeightOrPack("vol");

                }else if(tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("吨")
                        ||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("kg")
                        ||tFoFreightOrderItem.getShipbyQtyWeightOrPack().equals("t")){
                    tFoFreightOrderItem.setShipbyQtyWeightOrPack("weight");

                }
            }
            tFoFreightOrderItem.setSite(sysUser.getOrgId());
             tFoFreightOrderItem.setDropOffWarehouseNo(tbWmsMaterialDeliveryLineVo.getDeliveryWarehouseCode());
        tFoFreightOrderItem.setPickUpWarehouseNo(tbWmsMaterialDeliveryLineVo.getPickUpWarehouseNo());
        tFoFreightOrderItem.setTransitWarehouseNo(params.getTransitWarehouseNo());
        if(tFoFreightOrderItem.getOrderQuantity()==null){
            tFoFreightOrderItem.setOrderQuantity(new BigDecimal(1));
        }
        if(tFoFreightOrderItem.getDeliveryAddress()==null){
            tFoFreightOrderItem.setDeliveryAddress(deliverywarehouse.getAddress());
        }
     //      this.purchaseOrderItemMapper.insert(tFoFreightOrderItem);
        if(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()!=null){
            tFoFreightOrderItem.setDemandDeliveryDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()));
            tFoFreightOrderItem.setPromiseDeliveryDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()));
            tFoFreightOrderItem.setArrangedDeliveryDate(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getRequestDeliveryTime()));
        }
        tFoFreightOrderItem.setCustomerName(tbWmsMaterialDeliveryVo.getCustomerName());
        tFoFreightOrderItem.setConsigneeId(tbWmsMaterialDeliveryVo.getConsignee());
        if(StringUtils.isNull(tFoFreightOrderItem.getShipbyQtyWeightOrPack())){
            tFoFreightOrderItem.setShipbyQtyWeightOrPack("qty");
        }
        if(tFoFreightOrderItem.getPackQty()==null){
            tFoFreightOrderItem.setPackQty(new BigDecimal(1));
        }
        if(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime()!=null) {
            tFoFreightOrderItem.setEstPickUpTime(DateUtils.parseDate(tbWmsMaterialDeliveryLineVo.getPreviousDepartTime()));
        }else{
            tFoFreightOrderItem.setEstPickUpTime(new Date());
        }
        if(tFoFreightOrderItem.getEstPickUpTime()==null){
            tFoFreightOrderItem.setEstPickUpTime(new Date());
        }
            TbWmsMaterialDeliveryLine tbWmsMaterialDeliveryLine =
                    this.tbWmsMaterialDeliveryLineMapper.selectById(tbWmsMaterialDeliveryLineVo.getId());
            tbWmsMaterialDeliveryLine.setStatus(WmsOutStatusEnum.shipPlaned.getValue());
            tbWmsMaterialDeliveryLine.setFreightOrderNo(tFoFreightOrderItem.getPurchaseOrderNo());
            tbWmsMaterialDeliveryLine.preUpdate(sysUser.getId());
            this.tbWmsMaterialDeliveryLineMapper.updateById(tbWmsMaterialDeliveryLine);

        return "success";
    }
}
